const redis = require("redis");
const bluebird = require("bluebird");
const stripAnsi = require("strip-ansi");
const model = require("./model");
const config = require("./config");
const pub = require("./redis");
const jwt = require("jsonwebtoken");
const io = require("socket.io")(config.socket.port);

bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

const sub = redis.createClient(config.redis);

// 全局
global.BaaS = {};
global.BaaS.bookshelf = model.bookshelf;
global.BaaS.Models = model.Models;
global.BaaS.redis = pub;

/**
 * 任务初始化
 */
(async () => {
  io.on("connection", async socket => {
    const sid = socket.id;
    const { BaasToken } = socket.request._query;
    const { appid, appkey } = jwt.verify(BaasToken, config.jwt.secret);
    const key = `baas:2.0:appid:${appid}:appkey:${appkey}:socket`;
    await BaaS.redis.rpushAsync(key, sid);

    socket.on("disconnect", async () => {
      await BaaS.redis.lremAsync(key, 0, sid);
    });
  });

  sub.on("message", async (channel, message) => {
    if (channel === "baas:2.0:log") {
      const _message = JSON.parse(message);
      const { appid, appkey } = _message;
      const msg = _message.message;
      const key = `baas:2.0:appid:${appid}:appkey:${appkey}:socket`;
      const sidList = await BaaS.redis.lrangeAsync(key, 0, -1);
      for (const sid of sidList) {
        const ioSocket = io.sockets.sockets[sid];
        if (ioSocket) {
          ioSocket.emit("log", JSON.stringify({ message: stripAnsi(msg) }));
        }
      }
    }
  });

  sub.subscribe("baas:2.0:log");
})();
